package com.ruoyi.web.cp.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.SystemClock;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.core.config.ConfigLoader;
import com.ruoyi.web.cp.domain.rm.RmGame;
import com.ruoyi.web.cp.service.http.RmHttpService;
import com.ruoyi.web.cp.service.rm.RmGameService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.nio.file.FileSystems;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Service
public class RmService {
    @Autowired
    private ConfigLoader configLoader;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private RmHttpService rmHttpService;
    @Autowired
    private RmGameService rmGameService;
    private static Integer count = 0;

    /**
     * @Description: 获取rm列表
     * @Author: xiesm
     * @Date: 2025/3/21
     */
    public void getRmList() {
        Set<String> games = new LinkedHashSet<>();

        String res = rmHttpService.sendRmList();
        Document document = Jsoup.parse(res);
        Elements gameList = document.getElementsByClass("game_list");
        if (CollUtil.isEmpty(gameList)) {
            return;
        }
        count = 0;
        for (Element game : gameList) {
            Elements lis = game.select("li");
            for (Element element : lis) {
                try {
                    String onclick = element.attr("onclick");
                    //比赛id
                    String gameId = StringUtils.replace(onclick, "listmrketorder").get(0);
                    //比赛时间
                    String time = element.getElementsByClass("time").text();

                    String timeStr = time + ":00";
                    DateTime dateTime = DateUtil.parse(timeStr, "yyyy-MM-dd HH:mm:ss");
                    String tomorrow = DateUtil.format(DateUtil.offsetDay(new Date(), 1), "yyyy-MM-dd");
                    tomorrow = tomorrow + " 12:01:00";
                    DateTime tomorrowDate = DateUtil.parse(tomorrow, "yyyy-MM-dd HH:mm:ss");
                    if (dateTime.getTime() > tomorrowDate.getTime()) {
                        continue;
                    }

                    if (SystemClock.now() > dateTime.getTime()) {
                        continue;
                    }

                    //联赛名称
                    String[] names = element.getElementsByClass("game_name").html().split(" ");
                    String name = names[names.length - 1];
                    //队伍名称
                    Elements teams = element.getElementsByClass("game_team");
                    String team1 = teams.get(0).text();
                    team1 = team1.substring(0, team1.indexOf("("));
                    String team2 = teams.get(1).text();

                    String str = StrUtil.format("{}\t{}\t{}\t{}\t{}", gameId, name, time, team1, team2);
                    games.add(str);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        if (CollUtil.isNotEmpty(games)) {
            FileUtil.writeLines(games, configLoader.getRmPath() + "rm-game.txt", "utf8");
            rmGameService.saveRmGame(new ArrayList<>(games));
        }
    }

    private final ReentrantLock lock = new ReentrantLock();

    /**
     * @Description: 获取rm详情
     * @Author: xiesm
     * @Date: 2025/3/21
     */
    public void getRmDetail() {
        lock.lock();
        try {
            // 原方法逻辑
            log.info("======> 获取rm详情开始");
            long beginTime = System.currentTimeMillis();
            List<String> games = FileUtil.readLines(configLoader.getRmPath() + "rm-game.txt", "utf8");
            List<String> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            List<String> list3 = new ArrayList<>();
            List<String> listSou5 = new ArrayList<>();
            List<String> listSou10 = new ArrayList<>();

            for (String game : games) {
                try {
                    list1.add(game);
                    list2.add(game);
                    listSou5.add(game);
                    listSou10.add(game);
                    String[] strs = game.split("\t");

                    List<RmGame.Detail> halfDetail = new ArrayList<>();
                    List<RmGame.Detail> allDetail = new ArrayList<>();
                    List<RmGame.Detail> goalTime5Detail = new ArrayList<>();
                    List<RmGame.Detail> goalTime10Detail = new ArrayList<>();

                    String res = rmHttpService.sendRmDetail(strs[0].trim(), game);
                    if (res == null) {
                        continue;
                    }
                    Document document = Jsoup.parse(res);
                    Elements types = document.getElementsByClass("table_wrap");
                    String dateStr = null;
                    //全场波胆
                    for (Element type : types) {
                        Elements contentRows = type.getElementsByClass("content_row");
                        for (Element row : contentRows) {
                            String onclick = row.attr("onclick");
                            List<String> list = StringUtils.replace(onclick, "setBet");
                            dateStr = dateStr == null ? list.get(2) : dateStr;
                            String bodan = list.get(4).replace(" ", "");
                            String score = list.get(5).replace(" ", "");
                            String plv = list.get(6);
                            if (StrUtil.isNotEmpty(plv)) {
                                plv = new BigDecimal(plv).multiply(new BigDecimal("100")).stripTrailingZeros().toString();
                            }
                            String str = StrUtil.format("{}\t{}", score, plv);
                            if ("波胆".equals(bodan) && StrUtil.isNotEmpty(plv)) {
                                list1.add(str);
                                allDetail.add(new RmGame.Detail(score, plv));
                            }
                            if ("半场波胆".equals(bodan) && StrUtil.isNotEmpty(plv) && !"其他".equals(score)) {
                                list2.add(str);
                                halfDetail.add(new RmGame.Detail(score, plv));
                            }
                            if ("首入球时间5分".equals(bodan) && StrUtil.isNotEmpty(plv) && !"终场没进球".equals(score)) {
                                listSou5.add(str);
                                goalTime5Detail.add(new RmGame.Detail(score, plv));
                            }
                            if ("首入球时间10分".equals(bodan) && StrUtil.isNotEmpty(plv) && !"终场没进球".equals(score)) {
                                listSou10.add(str);
                                goalTime10Detail.add(new RmGame.Detail(score, plv));
                            }
                        }
                    }
                    Elements chatShowIcons = document.getElementsByClass("chatShowIcon");
                    if (CollUtil.isNotEmpty(chatShowIcons)) {
                        String onclick = chatShowIcons.get(0).attr("onclick");
                        List<String> list = StringUtils.replace(onclick, "chatShow");
                        list3.add(StrUtil.format("{}\t{}\t{}\t{}\t{}\t{}",
                                list.get(0).trim(), list.get(1).trim(), dateStr, list.get(2), list.get(3).split("v")[0],
                                list.get(3).split("v")[1]));
                    }

                    rmGameService.saveRmGamePlv(new RmGame(strs[0].trim(), halfDetail, allDetail, goalTime5Detail, goalTime10Detail));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            FileUtil.writeLines(list1, configLoader.getRmPath() + "rm-gameScore.txt", "utf8");
            FileUtil.writeLines(list2, configLoader.getRmPath() + "rm-gameScore-half.txt", "utf8");
            FileUtil.writeLines(list3, configLoader.getRmPath() + "rm-chatShow.txt", "utf8");
            FileUtil.writeLines(listSou5, configLoader.getRmPath() + "rm-gameScore-sou5.txt", "utf8");
            FileUtil.writeLines(listSou10, configLoader.getRmPath() + "rm-gameScore-sou10.txt", "utf8");
            log.info(StrUtil.format("======> 获取rm详情结束,耗时:{}", (System.currentTimeMillis() - beginTime)));
        } finally {
            lock.unlock();
        }

    }

    public void removeRmGame(Set<String> names) {
        List<String> games = FileUtil.readLines(configLoader.getRmPath() + "rm-game.txt", "utf8");
        for (String game : games) {
            String[] split = game.split("\t");
            if (names.contains(split[3])) {
                String path = configLoader.getGamenamesPath() + "rm-gamescore" + FileSystems.getDefault().getSeparator() + split[0] + ".txt";
                FileUtils.delGame(split[3], "rm", split[0], path);
            }
        }
    }

    public void updateRmDetail() {
        List<String> games = FileUtil.readLines(configLoader.getRmPath() + "rm-game.txt", "utf8");
        for (String game : games) {
            String[] strs = game.split("\t");
            rmHttpService.updateRmDetail(strs[0].trim(), game);
        }
    }
}
